<?php
Yii::import('application.components.Reference');
class ReturJualController extends GxController
{
    public function actionCreate()
    {
        if (!Yii::app()->request->isAjaxRequest) return;
        if (isset($_POST) && !empty($_POST)) {
            $is_new = $_POST['mode'] == 0;
            $is_final = true;
            $retur_jual_id = $_POST['id'];
            $status = false;
            $msg = 'Retur penjualan berhasil disimpan.';
            Yii::import('application.components.U');
            $detils = CJSON::decode($_POST['detil']);
            if (isset($_POST['parent']) && !empty($_POST['parent'])) {
                $cek = Penjualan::model()->count('parent = :parent', array(':parent' => $_POST['parent']));
                if ($cek > 0) {
                    echo CJSON::encode(array(
                        'success' => false,
                        'id' => -1,
                        'msg' => 'Retur jual sudah pernah dibuat!'));
                    Yii::app()->end();
                }
            }
//            $kredit_piutang = CJSON::decode($_POST['kredit_piutang']);
            app()->db->autoCommit = false;
            $transaction = Yii::app()->db->beginTransaction();
            try {
                $retur_jual = $is_new ? new Penjualan : $this->loadModel($retur_jual_id,
                    "Penjualan");
                $docref = $retur_jual->doc_ref;
                if ($is_new) {
                    $ref = new Reference();
                    $docref = $ref->get_next_reference(RETURJUAL);
                }
                foreach ($_POST as $k => $v) {
                    if (is_angka($v)) $v = ($k == 'salesman_id' || $k == 'konsumen_id' ||
                        $k == 'parent') ? get_number($v) : -get_number($v);
                    $_POST['Penjualan'][$k] = $v;
                }
                $_POST['Penjualan']['doc_ref'] = $docref;
                $_POST['Penjualan']['arus'] = -1;
                $_POST['Penjualan']['id_user'] = Yii::app()->user->getId();
                $_POST['Penjualan']['final'] = 1;
                $_POST['Penjualan']['lunas'] = $_POST['Penjualan']['sisa_tagihan'] == 0 ? 1 : 0;
                $retur_jual->attributes = $_POST['Penjualan'];
                if (!$retur_jual->save())
                    throw new Exception("Gagal menyimpan retur jual. " . CHtml::errorSummary($retur_jual));
                $ppn = $hpp = 0;
                foreach ($detils as $detil) {
                    $retur_jual_detil = new DetilPenjualan;
                    $_POST['DetilPenjualan']['barang_id'] = $detil['barang_id'];
                    $_POST['DetilPenjualan']['sat'] = $detil['sat'];
                    $_POST['DetilPenjualan']['jml'] = -get_number($detil['jml']);
                    $_POST['DetilPenjualan']['price'] = get_number($detil['price']);
                    $_POST['DetilPenjualan']['disc1'] = get_number($detil['disc1']);
                    $_POST['DetilPenjualan']['disc2'] = get_number($detil['disc2']);
                    $_POST['DetilPenjualan']['pot'] = get_number($detil['pot']);
                    $_POST['DetilPenjualan']['totalpot'] = -get_number($detil['totalpot']);
                    $_POST['DetilPenjualan']['nominal'] = -get_number($detil['nominal']);
                    $_POST['DetilPenjualan']['bruto'] = -get_number($detil['bruto']);
                    $_POST['DetilPenjualan']['pcs'] = -get_number($detil['pcs']);
                    $_POST['DetilPenjualan']['hpp'] = -get_number($detil['hpp']);
                    $_POST['DetilPenjualan']['penjualan_id'] = $retur_jual->penjualan_id;
                    $retur_jual_detil->attributes = $_POST['DetilPenjualan'];
                    if (!$retur_jual_detil->save())
                        throw new Exception("Gagal menyimpan retur jual detil. " . CHtml::errorSummary($retur_jual_detil));
                    if ($retur_jual_detil->barang->ppn) {
                        $ppn += ($retur_jual_detil->nominal) * (1 / 11);
                    }
                    $hpp_detil = $retur_jual_detil->barang->get_hpp($retur_jual_detil->pcs);
                    $hpp += $hpp_detil;
                    $retur_jual_detil->hpp = $hpp_detil;
                    if (!$retur_jual_detil->save())
                        throw new Exception("Gagal menyimpan hpp retur jual detil. " . CHtml::errorSummary($retur_jual_detil));
//                    $hpp += $retur_jual_detil->hpp;
                    U::add_stock_moves(RETURJUAL, $retur_jual->penjualan_id, $retur_jual->tgl,
                        $retur_jual_detil->barang_id, GUDANG_SMT, -$retur_jual_detil->pcs, $retur_jual->doc_ref,
                        $retur_jual_detil->price);
                }
                if ($is_new) {
                    $ref->save(RETURJUAL, $retur_jual->penjualan_id, $docref);
                }
                $is_agen = $retur_jual->konsumen->agen == 1;
                Yii::import('application.components.Gl');
                $gl = new Gl();
                $gl->add_gl(RETURJUAL, $retur_jual->penjualan_id, $retur_jual->tgl, $retur_jual->doc_ref,
                    KASSEMENTARA, '', '', $retur_jual->uang_muka);
                $gl->add_gl(RETURJUAL, $retur_jual->penjualan_id, $retur_jual->tgl, $retur_jual->doc_ref,
                    PIUTANGDAGANG, '', '', $retur_jual->sisa_tagihan);
                if ($ppn != 0) {
                    $gl->add_gl(RETURJUAL, $retur_jual->penjualan_id, $retur_jual->tgl, $retur_jual->doc_ref,
                        PPN, '', '', -$ppn);
                }
//                if ($retur_jual->disc != 0) {
//                    U::add_gl(RETURJUAL, $retur_jual->penjualan_id, $retur_jual->tgl, $retur_jual->doc_ref,
//                        $is_agen ? POTONGPENJUALANAGEN : POTONGPENJUALANSALES, '', '', $retur_jual->disc);
//                }
                $gl->add_gl(RETURJUAL, $retur_jual->penjualan_id, $retur_jual->tgl, $retur_jual->doc_ref,
                    $is_agen ? RETURPENJUALANAGEN : RETURPENJUALANSALES, '', '', -($retur_jual->total - $ppn));
                // hpp debet
                $gl->add_gl(RETURJUAL, $retur_jual->penjualan_id, $retur_jual->tgl, $retur_jual->doc_ref,
                    HPP, '', '', $hpp);
                // persediaan kredit
                $gl->add_gl(RETURJUAL, $retur_jual->penjualan_id, $retur_jual->tgl, $retur_jual->doc_ref,
                    PERSEDIANBARANGDAGANG, '', '', -$hpp);
                $gl->validate();
                $transaction->commit();
                $status = true;
            } catch (Exception $ex) {
                $transaction->rollback();
                $status = false;
                $msg = $ex->getMessage();
            }
            echo CJSON::encode(array(
                'success' => $status,
                'id' => $docref,
                'msg' => $msg));
            Yii::app()->end();
        }
    }
    public function actionUpdate($id)
    {
        $model = $this->loadModel($id, 'ReturJual');
        if (isset($_POST) && !empty($_POST)) {
            foreach ($_POST as $k => $v) {
                if (is_angka($v)) $v = get_number($v);
                $_POST['ReturJual'][$k] = $v;
            }
            $msg = "Data gagal disimpan";
            $model->attributes = $_POST['ReturJual'];
            if ($model->save()) {
                $status = true;
                $msg = "Data berhasil di simpan dengan id " . $model->retur_jual_id;
            } else {
                $msg .= " " . CHtml::errorSummary($model);
                $status = false;
            }
            if (Yii::app()->request->isAjaxRequest) {
                echo CJSON::encode(array(
                    'success' => $status,
                    'msg' => $msg
                ));
                Yii::app()->end();
            } else {
                $this->redirect(array('view', 'id' => $model->retur_jual_id));
            }
        }
    }
    public function actionDelete($id)
    {
        if (Yii::app()->request->isPostRequest) {
            $msg = 'Data berhasil dihapus.';
            $status = true;
            try {
                $this->loadModel($id, 'ReturJual')->delete();
            } catch (Exception $ex) {
                $status = false;
                $msg = $ex->getMessage();
            }
            echo CJSON::encode(array(
                'success' => $status,
                'msg' => $msg));
            Yii::app()->end();
        } else
            throw new CHttpException(400,
                Yii::t('app', 'Invalid request. Please do not repeat this request again.'));
    }
    public function actionIndex()
    {
        Yii::import('application.components.U');
//        $tgl = $_POST['tgl'];
//        $sales = $_POST['sales'];
        $retur = U::get_retur_jual();
        $total = count($retur);
        $jsonresult = '{"total":"' . $total . '","results":' . json_encode($retur) . '}';
        Yii::app()->end($jsonresult);
    }
}